﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using WebSocketSharp;

namespace Service.Net.WebSocket
{
    /// <summary>
    /// Class WebSocketHelper.
    /// </summary>
    public static class WebSocketHelper
    {
        /// <summary>
        /// Internets the state of the get connected.
        /// </summary>
        /// <param name="Description">The description.</param>
        /// <param name="ReservedValue">The reserved value.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);

        /// <summary>
        /// 是否启动
        /// </summary>
        private static bool isStart = false;

        /// <summary>
        /// The is flag
        /// </summary>
        private static bool isFlag = true;

        /// <summary>
        /// 启动实例.
        /// </summary>
        /// <param name="deviceId">设备id.</param>
        /// <param name="getMessage">消息回调.</param>
        public static void Start(string deviceId, EventHandler<MessageEventArgs> getMessage)
        {
            Task.Factory.StartNew(() =>
            {
                if (isStart)
                    return;
                isStart = true;

                while (true)
                {
                    try
                    {
                        if (InternetGetConnectedState(0, 0))
                        {
                            #region 启动WebSocket

                            isFlag = true;
                            var webSocket = ConfigurationManager.AppSettings["WebSocket"];
                            using (var ws = new WebSocketSharp.WebSocket($"{webSocket}/{deviceId}"))
                            {
                                ws.OnMessage += getMessage;
                                ws.OnClose += (a, b) =>
                                {
                                    isFlag = false;
                                };

                                ws.OnError += (a, b) =>
                                {
                                    isFlag = false;
                                    Trace.TraceError(b.Message);
                                };

                                ws.Connect();
                                while (isFlag)
                                {
                                    ws.SendAsync("", (isSuccess) =>
                                    {
                                        if (!isSuccess)
                                            isFlag = false;
                                    });

                                    Thread.Sleep(1000);
                                }
                            }

                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError(ex.Message);
                    }
                    Thread.Sleep(1000);
                }
            });
        }

    }
}
